package com.seele.tigerwallet.ui.popupwindow;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.seele.tigerwallet.R;
import com.seele.tigerwallet.model.TransferErrorModel;
import com.seele.tigerwallet.ui.utils.GsonUtil;
import com.seele.tigerwallet.ui.utils.SPUtils;
import com.seele.tigerwallet.utils.EthWalletUtil;

public class PwdPopupWindow extends PopupWindow {
    private int mWidth;
    private int mHeight;
    private View mContentView;
    private ListView mListView;
    private int currentIndex = -1; // 用于记录当前输入密码格位置
    private boolean mIsPwdAgain = false;
    private Context mContext;
    private Button mBtnImport;
    private TextView mTvPwdTitle;
    private TextView[] mTvPwd = new TextView[6];
    private TextView[] mBtnInput = new TextView[12];
    private OnPasswordLisenter mOnPasswordLisenter;
    private ImageView mImageViewClose;
    private Handler mHandler;
    private static final String TAG = "PwdPopupWindow";
    private int flag;
    private int cout = 5;
    private String password = "";
    private long dif = 60000 * 60 * 2;

    public PwdPopupWindow(Context context) {
        super(context);
        mContext = context;
        initView();
        flag = 0;
    }

    public String getPassword() {
        return password;
    }

    private void initView() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_wallet_password,null);
        setContentView(view);
        currentIndex = -1;
        mIsPwdAgain = false;
        calWidthAndHeight(mContext);
        setWidth(mWidth);
        setHeight(mHeight);
        setFocusable(true);
        setTouchable(true);
        setTouchable(true);
        this.setClippingEnabled(false);
        ColorDrawable dw = new ColorDrawable(-00000);
        this.setBackgroundDrawable(dw);
        mImageViewClose = (ImageView) view.findViewById(R.id.imageview);
        mImageViewClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PwdPopupWindow.this.dismiss();
            }
        });
        LinearLayout deleteLayout = (LinearLayout) view.findViewById(R.id.layout_delete);
        deleteLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentIndex - 1 >= -1) { // 判断是否删除完毕————要小心数组越界
                    mTvPwd[currentIndex--].setText("");
                }
            }
        });

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                onPwdOk();
            }
        };

        mTvPwdTitle = (TextView) view.findViewById(R.id.tv_pwd_title);
        for (int i = 0; i < 6; i++) {
            int textViewId = mContext.getResources().getIdentifier("tv_pass" + i, "id", mContext.getPackageName());
            mTvPwd[i] = (TextView) view.findViewById(textViewId);
        }

        for (int i = 0; i < 12; i++) {
            int textViewId = mContext.getResources().getIdentifier("btn_key" + i, "id", mContext.getPackageName());
            mBtnInput[i] = (TextView) view.findViewById(textViewId);
            mBtnInput[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.i(TAG, "onClick.");
                    onInputClick(v);
                }
            });
        }

        setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    dismiss();
                }
                return false;
            }
        });
    }


    public void dismiss() {
        super.dismiss();
        //password = "";
        System.gc();
    }

    public void showAtLocation(Activity acitivity) {
        this.showAtLocation(acitivity.getWindow().getDecorView(), Gravity.TOP | Gravity.RIGHT, 0, 0);
    }


    public void onInputClick(View view) {
        if (view.getId() == R.id.btn_key11) {
            if (currentIndex - 1 >= -1) { // 判断是否删除完毕————要小心数组越界
                mTvPwd[currentIndex--].setText("");
            }
        } else {
            String text = ((TextView) view).getText().toString();
            Log.i(TAG, "text:" + text);
            if (text.charAt(0) >= '0' && text.charAt(0) <= '9') { // 点击0~9按钮
                if (currentIndex >= -1 && currentIndex < 6 ) { // 判断输入位置————要小心数组越界
                    mTvPwd[++currentIndex].setText(text);
                }
                if (currentIndex == 5) {
                    password = "";
                    for (int i = 0; i < 6; i++) {
                        password += mTvPwd[i].getText();
                    }
                    dismiss();
                    mOnPasswordLisenter.onInputEnd(password);
                    //mHandler.obtainMessage(0).sendToTarget();
                    //dismiss();
                }
            }
        }
    }


    public void setOnPasswordLisenter(OnPasswordLisenter lisenter) {
        this.mOnPasswordLisenter = lisenter;
    }

    public interface OnPasswordLisenter {
        public void onInputEnd(String password);
    }

    private void onPwdOk() {
        boolean isTransfer = true;
        String value = SPUtils.getString(SPUtils.TRANSFER_TIME);
        password = "";
        for (int i = 0; i < 6; i++) {
            password += mTvPwd[i].getText();
        }

        if (!TextUtils.isEmpty(value)) {

            TransferErrorModel transferErrorModel = GsonUtil.parseJsonWithGson(value, TransferErrorModel.class);
            if (transferErrorModel.isError) {//曾经输错过密码
                long timeMillis = System.currentTimeMillis();
                if (timeMillis - transferErrorModel.time < dif) {
                    isTransfer = false;
                } else {
                    isTransfer = true;
                }
            }else {
                isTransfer = true;
            }
        }

        if (!isTransfer){
            toast();
            setkeyboard();
            return;

        }
        boolean isOk = EthWalletUtil.checkPassowrd(password);


        //String pwdMd5 = WalletManager.getInstance().getCurrentEthWallet().passwordMd5;
        if (isOk) {
            //密码校验正确，转账
            //mOnPasswordLisenter.onPwdOk();
            this.dismiss();
        } else {
            Toast.makeText(mContext, "密码错误,请重新输入密码.", Toast.LENGTH_LONG).show();
            password = "";
            mTvPwdTitle.setText(R.string.password_title);
            currentIndex = -1;
            mIsPwdAgain = false;

            for (int i = 0; i < 6; i++) {
                mTvPwd[i].setText("");
            }
            flag++;
            switch (flag) {
                case 1:
                    onToast(cout - 1);
                    break;
                case 2:
                    onToast(cout - 2);
                    break;
                case 3:
                    onToast(cout - 3);
                    break;

                case 4:
                    onToast(cout - 4);
                    break;
                case 5:
                    //密码输错5次
                    TransferErrorModel transferErrorModel = new TransferErrorModel();
                    toast();
                    transferErrorModel.isError = true;
                    transferErrorModel.time = System.currentTimeMillis();
                    SPUtils.putString(SPUtils.TRANSFER_TIME, GsonUtil.toJsonString(transferErrorModel));
                    break;
            }

            setkeyboard();
        }
    }

    private void setkeyboard() {
        String secondPassord;
        secondPassord = "";
        mTvPwdTitle.setText(R.string.password_title);
        currentIndex = -1;
        mIsPwdAgain = false;

        for (int i = 0; i < 6; i++) {
            mTvPwd[i].setText("");
        }
    }

    private void toast() {
        Toast.makeText(mContext, mContext.getResources().getString(R.string.transfer_password_error_time), Toast.LENGTH_SHORT).show();
    }

    public void onToast(int count) {
        String tostString = String.format(mContext.getResources().getString(R.string.transfer_password_error), count);
        Toast.makeText(mContext, tostString, Toast.LENGTH_SHORT).show();
    }

    private void showPassword() {
        Log.i(TAG, "Mnemonic select end.");
        currentIndex = -1;
        mIsPwdAgain = false;

        for (int i = 0; i < 6; i++) {
            mTvPwd[i].setText("");
        }

        for (int i = 0; i < 12; i++) {

        }

    }


    /**
     * 设置PopupWindow的大小
     *
     * @param context
     */
    private void calWidthAndHeight(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(metrics);

        mWidth = metrics.widthPixels;
        //设置高度为全屏高度的70%
        mHeight = (int) (metrics.heightPixels);
    }

}
